#include "Connection.h"

#include <iostream>

Connection::Connection()
    : last_operation_time_(std::chrono::steady_clock::now())
{
    conn_ = mysql_init(nullptr);
}

Connection::~Connection()
{
    if (conn_ != nullptr)
        mysql_close(conn_);
}

bool Connection::connect(string ip, unsigned short port,
    string user, string password, string dbname)
{
    MYSQL *p = mysql_real_connect(conn_, ip.c_str(),
        user.c_str(), password.c_str(), dbname.c_str(), port, nullptr, 0);
    
    if (p == nullptr)
    {
        std::cerr << "数据库连接失败: " << mysql_error(conn_) 
                  << ", 错误代码: " << mysql_errno(conn_) <<  std::endl;
        // 关闭连接并释放资源
        mysql_close(conn_);
    }

    return p != nullptr;
}

bool Connection::update(string sql)
{
    if (mysql_query(conn_, sql.c_str()))
    {
        std::cout << "更新失败: " << sql << ", "
                  << mysql_error(conn_) << std::endl;
        return false;
    }
    return true;
}

MYSQL_RES* Connection::query(string sql)
{
    if (mysql_query(conn_, sql.c_str()))
    {
        std::cout << "查询失败: " << sql << ", "
                  << mysql_error(conn_) << std::endl;
        return nullptr;
    }

    return mysql_use_result(conn_);
}

void Connection::updateLastOperationTime()
{
    last_operation_time_ = std::chrono::steady_clock::now();
}

uint64_t Connection::getIdleTimeMillis() const 
{
  auto now = std::chrono::steady_clock::now();
  return std::chrono::duration_cast<std::chrono::milliseconds>(
             now - last_operation_time_).count();
}